package com.xmjs.baselibrary.view.recyclerview.pull;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import static com.xmjs.baselibrary.view.recyclerview.pull.DIRECTION.DOWN;
import static com.xmjs.baselibrary.view.recyclerview.pull.DIRECTION.UP;

/**
 * 可自定义下拉刷新/上拉加载更多的RecyclerView
 */
public class PullRecyclerView extends RecyclerView {
    public static final int HEAD_STATE_NORMAL = 0;
    public static final int HEAD_STATE_RELEASE_TO_REFRESH = 1;
    public static final int HEAD_STATE_REFRESHING = 2;
    public static final int HEAD_STATE_DONE = 3;
    public static final int HEAD_STATE_FAIL = 4;

    public static final int MORE_STATE_NORMAL = 0;
    public static final int MORE_STATE_REFRESHING = 1;
    public static PullSysConfig mSysConfig;
    private Context mContext;
    //摩擦力
    private static final int DRAG_RATE = 2;
    private final AdapterDataObserver dataObserver = new DataObserver();
    private PullToRefreshRecyclerViewAdapter pullToRefreshRecyclerViewAdapter;
    private PullListener pullListener;
    private ScrollListener scollListener;
    //下拉刷新视图
    private AbRefreshHeadView mHeadRefreshView;
    //上拉加载更多视图
    private AbRefreshMoreView mMoreRefreshView;
    private int mHeadRefreshState = HEAD_STATE_NORMAL;
    private int mMoreRefreshState = MORE_STATE_NORMAL;
    //是否允许上拉加载更多
    private boolean isCanLoadMore = false;
    //是否允许下拉刷新
    private boolean isCanRefresh = false;
    //上一次滚动的位置
    private float lastY = -1;
    //是否正在执行刷新中
    //private boolean isRefreshing;
    //总偏移量
    private int y;

    public PullRecyclerView(Context context) {
        this(context, null);
    }

    public PullRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PullRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public static void setPullSysConfig(PullSysConfig config) {
        mSysConfig = config;
    }

    private boolean isExistRefreshView() {
        return mHeadRefreshView != null;
    }

    private boolean isExistLoadMoreView() {
        return mMoreRefreshView != null;
    }

    public boolean isCanRefresh() {
        return isCanRefresh && isExistRefreshView();
    }

    public boolean isCanLoadMore() {
        return isCanLoadMore && isExistLoadMoreView();
    }

    /**
     * 是否正常加载更多中
     *
     * @return
     */
    public boolean isLoadMore() {
        return mMoreRefreshState == MORE_STATE_REFRESHING && isExistLoadMoreView();
    }

    /**
     * 是否正在刷新中
     *
     * @return
     */
    public boolean isRefresh() {
        return mHeadRefreshState == HEAD_STATE_REFRESHING && isExistRefreshView();
    }

    /**
     * 设置是否允许下拉刷新
     *
     * @param refresh
     * @return
     */
    public PullRecyclerView setUseRefresh(boolean refresh) {
        isCanRefresh = refresh;
        return this;
    }

    /**
     * 设置是否允许上拉加载更多
     *
     * @param loadMore
     * @return
     */
    public PullRecyclerView setUseLoadMore(boolean loadMore) {
        if (isExistLoadMoreView()) {
            int visib = mMoreRefreshView.getVisibility();
            if (visib != (loadMore ? VISIBLE : GONE)) {
                mMoreRefreshView.setVisibility(loadMore ? VISIBLE : GONE);
            }
        }
        isCanLoadMore = loadMore;
        return this;
    }

    /**
     * 设置item动画
     *
     * @param animator
     * @return
     */
    public PullRecyclerView setPullItemAnimator(ItemAnimator animator) {
        setItemAnimator(animator);
        return this;
    }

    /**
     * 设置刷新视图
     *
     * @param headView
     * @return
     */
    public PullRecyclerView setHeadRefreshView(AbRefreshHeadView headView) {
        this.mHeadRefreshView = headView;
        return this;
    }

    /**
     * 设置加载更多视图
     *
     * @param moreRefreshView
     * @return
     */
    public PullRecyclerView setMoreRefreshView(AbRefreshMoreView moreRefreshView) {
        this.mMoreRefreshView = moreRefreshView;
        return this;
    }

    /**
     * 设置下拉刷新/上拉加载更多的监听器
     *
     * @param pullListener
     * @return
     */
    public PullRecyclerView setPullListener(PullListener pullListener) {
        this.pullListener = pullListener;
        return this;
    }

    /**
     * 设置滚动监听器
     *
     * @param scollListener
     * @return
     */
    public PullRecyclerView setScollListener(ScrollListener scollListener) {
        this.scollListener = scollListener;
        return this;
    }

    /**
     * 设置LayoutManager
     *
     * @param layout
     * @return
     */
    public PullRecyclerView setPullLayoutManager(LayoutManager layout) {
        setLayoutManager(layout);
        return this;
    }

    private void init(Context context) {
        mContext = context;
        initPullConfig();
        setUseLoadMore(isCanLoadMore());
        //监听RecyclerView的滚动事件
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                y += dy;
                requestLayout();
                //第一个可见item的位置
                int firstVisibleItemPosition = 0;
                //最后一个可见item的位置
                int lastVisibleItemPosition = 0;
                if (getLayoutManager() instanceof LinearLayoutManager) {
                    firstVisibleItemPosition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
                    lastVisibleItemPosition = ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
                }
                firstVisibleItemPosition = (firstVisibleItemPosition - 1) < 0 ? 0 : (firstVisibleItemPosition - 1);
                lastVisibleItemPosition = lastVisibleItemPosition < 0 ? 0 : lastVisibleItemPosition;
                if (scollListener != null)
                    scollListener.onScrolled(y, dy < 0 ? UP : DOWN, firstVisibleItemPosition, lastVisibleItemPosition);
            }
        });
    }

    @Override
    public void scrollToPosition(int position) {
        super.scrollToPosition(position);
        y = 0;
    }

    /**
     * 事件分发
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //正在刷新时，禁止事件分发，也就是禁止任何操作
        //  if (isRefreshing)
        //      return true;
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 初始化系统级配置
     */
    private void initPullConfig() {
        if (mSysConfig != null) {
            try {
                Class<? extends AbRefreshHeadView> refreshCls = mSysConfig.getRefreshViewClass();
                if (refreshCls != null) {
                    Constructor cst = refreshCls.getDeclaredConstructor(Context.class);
                    mHeadRefreshView = (AbRefreshHeadView) cst.newInstance(mContext);
                }
                Class<? extends AbRefreshMoreView> moreCls = mSysConfig.getMoreViewClass();
                if (moreCls != null) {
                    Constructor cst = moreCls.getDeclaredConstructor(Context.class);
                    mMoreRefreshView = (AbRefreshMoreView) cst.newInstance(mContext);
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置适配器
     *
     * @param adapter
     */
    @Override
    public void setAdapter(Adapter adapter) {
        //注册数据观察者
        dataObserver.onChanged();
        adapter.registerAdapterDataObserver(dataObserver);

        //自定义适配器
        pullToRefreshRecyclerViewAdapter = new PullToRefreshRecyclerViewAdapter(adapter);
        //传递适配器
        super.setAdapter(pullToRefreshRecyclerViewAdapter);
        //隐藏加载更多视图
        if (mMoreRefreshView != null) mMoreRefreshView.setVisibility(GONE);
    }

    /**
     * 获取适配器
     *
     * @return
     */
    @Override
    public Adapter getAdapter() {
        if (pullToRefreshRecyclerViewAdapter != null) {
            return pullToRefreshRecyclerViewAdapter.getAdapter();
        }
        return null;
    }

    /**
     * 设置LayoutManager
     *
     * @param layout
     */
    @Override
    public void setLayoutManager(LayoutManager layout) {
        super.setLayoutManager(layout);
        if (pullToRefreshRecyclerViewAdapter != null) {
            if (layout instanceof GridLayoutManager) {
                final GridLayoutManager gridManager = ((GridLayoutManager) layout);
                gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return (pullToRefreshRecyclerViewAdapter.isLoadMoreFooter(position)
                                || pullToRefreshRecyclerViewAdapter.isRefreshHeader(position))
                                ? gridManager.getSpanCount() : 1;
                    }
                });

            }
        }
    }

    /**
     * 手势事件
     *
     * @param e
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastY = e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (isCanRefresh) {
                    lastY = lastY == -1 ? e.getRawY() : lastY;
                    float moveY = e.getRawY() - lastY;
                    lastY = e.getRawY();
                    if (isCanRefresh() && mHeadRefreshView.getVisibleHeight() == 0 && moveY < 0) {
                        return super.onTouchEvent(e);
                    }
                    if (isOnTop() && !isRefresh()) {
                        onMove((int) (moveY / DRAG_RATE));
                        return false;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                checkRefresh();
                break;
        }
        return super.onTouchEvent(e);
    }

    /**
     * 触摸事件结束后检查是否需要刷新
     */
    private void checkRefresh() {
        if (isCanRefresh()) {
            if (mHeadRefreshView.getVisibleHeight() <= 0) {
                return;
            }
            if (mHeadRefreshState == HEAD_STATE_NORMAL) {
                mHeadRefreshView.smoothScrollTo(0, scollListener);
                mHeadRefreshState = HEAD_STATE_DONE;
            } else if (mHeadRefreshState == HEAD_STATE_RELEASE_TO_REFRESH) {
                setRefreshState(HEAD_STATE_REFRESHING);
            }
        }
    }

    /**
     * 移动RecyclerView（伪移动，实际是动态设置刷新视图的高度）
     *
     * @param move
     */
    private void onMove(int move) {
        if (isCanRefresh() && !isRefresh()) {
            //计算得到下拉高度
            int newVisibleHeight = mHeadRefreshView.getVisibleHeight() + move;
            //已经下拉到限定值，可以准备开始执行刷新任务
            if (newVisibleHeight >= mHeadRefreshView.getRefreshHeight() && mHeadRefreshState != HEAD_STATE_RELEASE_TO_REFRESH) {
                mHeadRefreshState = HEAD_STATE_RELEASE_TO_REFRESH;
                mHeadRefreshView.onReleaseState();
            }
            //正在下拉过程中
            if (newVisibleHeight < mHeadRefreshView.getRefreshHeight() && mHeadRefreshState != HEAD_STATE_NORMAL) {
                mHeadRefreshState = HEAD_STATE_NORMAL;
                mHeadRefreshView.onPullingDown();
            }
            //动态设置刷新视图的高度
            mHeadRefreshView.setVisibleHeight(mHeadRefreshView.getVisibleHeight() + move);

            if (scollListener != null)
                scollListener.onPull((mHeadRefreshView.getVisibleHeight() + move));
        }
    }

    /**
     * 设置刷新状态
     *
     * @param state
     */
    private void setRefreshState(int state) {
        if (isExistRefreshView() && mHeadRefreshState != state) {
            switch (state) {
                case HEAD_STATE_REFRESHING://切换到刷新状态
                    //   isRefreshing = true;
                    mHeadRefreshView.onRefreshing();
                    mHeadRefreshView.smoothScrollTo(mHeadRefreshView.getRefreshHeight(), scollListener);
                    if (pullListener != null) {
                        pullListener.onRefresh();
                    }
                    break;
                case HEAD_STATE_DONE://切换到刷新完成或者加载成功的状态
                    if (mHeadRefreshState == HEAD_STATE_REFRESHING) {
                        mHeadRefreshView.onResultSuccess();
                        mHeadRefreshView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mHeadRefreshView.smoothScrollTo(0, scollListener);
                            }
                        }, 500);
                    }
                    break;
                case HEAD_STATE_FAIL://切换到刷新失败或者加载失败的状态
                    if (mHeadRefreshState == HEAD_STATE_REFRESHING) {
                        mHeadRefreshView.onResultFail();
                        mHeadRefreshView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mHeadRefreshView.smoothScrollTo(0, scollListener);
                            }
                        }, 500);
                    }
                    break;
            }
            mHeadRefreshState = state;
        }

    }

    /**
     * 判断列表是否滑到顶部
     */
    private boolean isOnTop() {
        return isExistRefreshView() && mHeadRefreshView.getParent() != null;
    }

    /**
     * 获取最大值
     *
     * @param lastPositions
     * @return
     */
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

    @Override
    public void onScrolled(int dx, int dy) {
        super.onScrolled(dx, dy);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        //显示/隐藏加载更多视图
        if (mMoreRefreshView != null)
            mMoreRefreshView.setVisibility(getAdapter().getItemCount() > 0
                    && getAdapter() != null ? VISIBLE : GONE);
        if (state == RecyclerView.SCROLL_STATE_IDLE//闲置状态
                && isCanLoadMore()//允许执行加载更多
                && !isLoadMore()//当前不在执行加载更多中
                && !isRefresh()) {//当前不在执行刷新中
            LayoutManager layoutManager = getLayoutManager();
            int lastCompletelyVisibleItemPosition;
            if (layoutManager instanceof GridLayoutManager) {
                lastCompletelyVisibleItemPosition = ((GridLayoutManager) layoutManager)
                        .findLastCompletelyVisibleItemPosition();
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                int[] into = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
                ((StaggeredGridLayoutManager) layoutManager).findLastCompletelyVisibleItemPositions(into);
                lastCompletelyVisibleItemPosition = findMax(into);
            } else {
                lastCompletelyVisibleItemPosition = ((LinearLayoutManager) layoutManager)
                        .findLastCompletelyVisibleItemPosition();
            }
            //滑到底部
            if (layoutManager.getChildCount() > 0 &&
                    lastCompletelyVisibleItemPosition == pullToRefreshRecyclerViewAdapter.getItemCount() - 1) {
                //执行加载更多的相关视图操作
                mMoreRefreshView.onLoadingMore();
                //执行加载更多的任务
                if (pullListener != null)
                    pullListener.onLoadMore();
                mMoreRefreshState = MORE_STATE_REFRESHING;
            }
        }
    }

    /**
     * 下拉刷新和下拉加载更多完成
     *
     * @param success 下拉或上滑是否成功
     */
    public void onComplete(boolean success) {
        if (isRefresh()) {
            if (success) {
                onRefreshComplete();
            } else {
                onRefreshFail();
            }

        }
        if (isLoadMore()) {
            if (success) {
                onLoadMoreComplete();
            } else {
                onLoadMoreFail();
            }
        }
    }


    /**
     * 下拉刷新完成
     */
    public void onRefreshComplete() {
        // isRefreshing = false;
        setRefreshState(HEAD_STATE_DONE);
    }

    /**
     * 下拉刷新失败
     */
    public void onRefreshFail() {
        setRefreshState(HEAD_STATE_FAIL);
    }

    /**
     * 上拉加载更多完成
     */
    public void onLoadMoreComplete() {
        if (isLoadMore()) {
            mMoreRefreshView.onResultSuccess();
            mMoreRefreshView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mMoreRefreshState = MORE_STATE_NORMAL;
                    mMoreRefreshView.onNormalState();
                }
            }, 500);
        }
    }

    /**
     * 上拉加载更多失败
     */
    public void onLoadMoreFail() {
        if (isLoadMore()) {
            mMoreRefreshView.onResultFail();
            mMoreRefreshView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mMoreRefreshState = MORE_STATE_NORMAL;
                    mMoreRefreshView.onNormalState();
                }
            }, 500);
        }
    }

    /**
     * 执行下拉刷新任务
     */
    public void onRefresh() {
        if (isCanRefresh() && !isLoadMore() && !isRefresh()) {
            mHeadRefreshState = HEAD_STATE_REFRESHING;
            mHeadRefreshView.onRefreshing();
            mHeadRefreshView.smoothScrollTo(mHeadRefreshView.getRefreshHeight(), scollListener);
            if (pullListener != null) {
                pullListener.onRefresh();
            }
        }
    }

    /**
     * 执行加载更多任务
     */
    public void onLoadMore() {
        if (isCanLoadMore() && !isLoadMore() && !isRefresh()) {
            mMoreRefreshState = MORE_STATE_REFRESHING;
            mMoreRefreshView.onLoadingMore();
            if (pullListener != null) {
                pullListener.onLoadMore();
            }
        }
    }

    /**
     * 自定义适配器，主要是添加刷新视图和加载更多视图
     */
    private class PullToRefreshRecyclerViewAdapter extends Adapter<ViewHolder> {
        private static final int TYPE_REFRESH_HEADER = 10000;//头部下拉刷新类型
        private static final int TYPE_LOAD_MORE_FOOTER = 10001;//底部加载更多类型
        private Adapter adapter;

        private PullToRefreshRecyclerViewAdapter(Adapter adapter) {
            this.adapter = adapter;
        }

        public Adapter getAdapter() {
            return adapter;
        }

        private boolean isLoadMoreFooter(int position) {
            return isExistLoadMoreView() && position == getItemCount() - 1;
        }

        /**
         * 判断当前位置的item是不是第1个，并且是刷新视图
         *
         * @param position
         * @return
         */
        private boolean isRefreshHeader(int position) {
            return isExistRefreshView() && position == 0;
        }

        /**
         * 判断类型是否是刷新视图或加载更多视图
         */
        private boolean isReservedItemViewType(int itemViewType) {
            return itemViewType == TYPE_REFRESH_HEADER || itemViewType == TYPE_LOAD_MORE_FOOTER;
        }

        @Override
        public int getItemCount() {
            int count = 0;

            if (isExistRefreshView()) {
                count++;
            }

            if (isExistLoadMoreView()) {
                count++;
            }

            if (adapter != null) {
                count += adapter.getItemCount();
            }
            return count;
        }

        @Override
        public int getItemViewType(int position) {
            //刷新视图类型
            if (isRefreshHeader(position)) {
                return TYPE_REFRESH_HEADER;
            }
            //加载更多视图类型
            if (isLoadMoreFooter(position)) {
                return TYPE_LOAD_MORE_FOOTER;
            }
            int adjPosition = position - 1;
            int adapterCount;
            if (adapter != null) {
                adapterCount = adapter.getItemCount();
                if (adjPosition < adapterCount) {
                    int type = adapter.getItemViewType(adjPosition);
                    if (isReservedItemViewType(type)) {
                        throw new IllegalStateException("PullToRefreshRecyclerView require itemViewType " +
                                "in adapter should be less than 10000 ");
                    }
                    return type;
                }
            }
            return 0;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_REFRESH_HEADER) {
                return new SimpleViewHolder(mHeadRefreshView);
            } else if (viewType == TYPE_LOAD_MORE_FOOTER) {
                return new SimpleViewHolder(mMoreRefreshView);
            }
            return adapter.onCreateViewHolder(parent, viewType);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (isRefreshHeader(position) || isLoadMoreFooter(position)) {
                return;
            }
            int adjPosition = position - (isExistRefreshView() ? 1 : 0);
            if (adapter != null) {
                adapter.onBindViewHolder(holder, adjPosition);
            }
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
            if (isRefreshHeader(position) || isLoadMoreFooter(position)) {
                return;
            }
            int adjPosition = position - (isExistRefreshView() ? 1 : 0);
            if (adapter != null) {
                if (payloads.isEmpty()) {
                    adapter.onBindViewHolder(holder, adjPosition);
                } else {
                    adapter.onBindViewHolder(holder, adjPosition, payloads);
                }
            }
        }

        @Override
        public long getItemId(int position) {
            if (isRefreshHeader(position) || isLoadMoreFooter(position)) {
                return -1;
            }
            int adjPosition = position - (isExistRefreshView() ? 1 : 0);
            if (adapter != null) {
                return adapter.getItemId(adjPosition);
            }
            return -1;
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            LayoutManager manager = recyclerView.getLayoutManager();
            if (manager instanceof GridLayoutManager) {
                final GridLayoutManager gridManager = ((GridLayoutManager) manager);
                gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return (isLoadMoreFooter(position) || isRefreshHeader(position))
                                ? gridManager.getSpanCount() : 1;
                    }
                });
            }
            adapter.onAttachedToRecyclerView(recyclerView);
        }

        @Override
        public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
            adapter.onDetachedFromRecyclerView(recyclerView);
        }

        @Override
        public void onViewAttachedToWindow(ViewHolder holder) {
            int viewType = holder.getItemViewType();
            if (viewType == TYPE_REFRESH_HEADER || viewType == TYPE_LOAD_MORE_FOOTER) {
                super.onViewAttachedToWindow(holder);
            } else {
                adapter.onViewAttachedToWindow(holder);
            }

            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams
                    && (isRefreshHeader(holder.getLayoutPosition()) || isLoadMoreFooter(holder.getLayoutPosition()))) {
                StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
                p.setFullSpan(true);
            }

        }

        @Override
        public void onViewDetachedFromWindow(ViewHolder holder) {
            adapter.onViewDetachedFromWindow(holder);
        }

        @Override
        public void onViewRecycled(ViewHolder holder) {
            adapter.onViewRecycled(holder);
        }

        @Override
        public boolean onFailedToRecycleView(ViewHolder holder) {
            return adapter.onFailedToRecycleView(holder);
        }

        @Override
        public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
            adapter.unregisterAdapterDataObserver(observer);
        }

        @Override
        public void registerAdapterDataObserver(AdapterDataObserver observer) {
            adapter.registerAdapterDataObserver(observer);
        }

        private class SimpleViewHolder extends ViewHolder {
            private SimpleViewHolder(View itemView) {
                super(itemView);
            }
        }

        public void setHasStableIds(boolean hasStableIds) {
            adapter.setHasStableIds(hasStableIds);
        }

    }

    /**
     * 设置适配器的数据观察者
     */
    private class DataObserver extends AdapterDataObserver {

        @Override
        public void onChanged() {
            if (pullToRefreshRecyclerViewAdapter != null) {
                pullToRefreshRecyclerViewAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            Log.e("bug", "--------onItemRangeInserted");
            pullToRefreshRecyclerViewAdapter.notifyItemRangeInserted(isExistRefreshView() ?
                    positionStart + 1 : positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeChanged(isExistRefreshView() ?
                    positionStart + 1 : positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeChanged(isExistRefreshView() ?
                    positionStart + 1 : positionStart, itemCount, payload);
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeRemoved(isExistRefreshView() ?
                    positionStart + 1 : positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemMoved(isExistRefreshView() ?
                    fromPosition + 1 : fromPosition, isExistRefreshView() ? toPosition + 1 : toPosition);
        }
    }

    /**
     * 系统级配置
     */
    public static class PullSysConfig {
        private Class<? extends AbRefreshHeadView> refreshViewClass;
        private Class<? extends AbRefreshMoreView> moreViewClass;

        private Class<? extends AbRefreshHeadView> getRefreshViewClass() {
            return refreshViewClass;
        }

        private Class<? extends AbRefreshMoreView> getMoreViewClass() {
            return moreViewClass;
        }

        private PullSysConfig(Builder builder) {
            refreshViewClass = builder.refreshViewClass;
            moreViewClass = builder.moreViewClass;
        }

        public static final class Builder {
            private Class<? extends AbRefreshHeadView> refreshViewClass;
            private Class<? extends AbRefreshMoreView> moreViewClass;

            public Builder refreshViewClass(Class<? extends AbRefreshHeadView> val) {
                refreshViewClass = val;
                return this;
            }

            public Builder moreViewClass(Class<? extends AbRefreshMoreView> val) {
                moreViewClass = val;
                return this;
            }

            public PullSysConfig build() {
                return new PullSysConfig(this);
            }
        }
    }

}
